In C programming, files are used to store and read data from external storage like a hard disk, USB drive, or network. Files are essential for permanent data storage or data sharing between different programs. C provides a standard library that contains functions to work with files. Files can be categorized into two types: text files and binary files.
Text files are human-readable files that store data in plain text format. Each line in a text file represents a record, and data is separated by delimiters like spaces, commas, etc.
Binary files store data in a format that is not human-readable. They are used to store non-text data like images, audio, video, etc.
In the following example, will create a text file, write data to it, read the data back, and then close the file.
#include <stdio.h>
int main() {
FILE *filePointer;
char data[100];
int num;
// Open the file in write mode
filePointer = fopen("sample.txt", "w");
// Check if the file was opened successfully
if (filePointer == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Write data to the file
fprintf(filePointer, "Hello, World!\n");
fprintf(filePointer, "This is a sample text file.\n");
fprintf(filePointer, "12345\n");
// Close the file
fclose(filePointer);
// Open the file in read mode
filePointer = fopen("sample.txt", "r");
// Check if the file was opened successfully
if (filePointer == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Read data from the file and print it
printf("Data from the file:\n");
while (fscanf(filePointer, "%s", data) != EOF) {
printf("%s ", data);
}
printf("\n");
// Close the file
fclose(filePointer);
return 0;
}
Data from the file:
Hello, World! This is a sample text file. 12345
What is a C file?
What is the purpose of fopen() in C?
What function is used to read data from a file in C?
What function is used to write data to a file in C?
What is the purpose of fclose() in C?